import os
import sys
from pathlib import Path

# 添加项目根目录到 Python 路径
root_dir = Path(__file__).parent.parent
sys.path.append(str(root_dir))

from flask import Flask, render_template, Response, send_from_directory
import requests
from flask_cors import CORS
from web.routes.udf_routes import udf_bp
from web.routes.chart_routes import chart_bp
from web.routes.favorite_routes import favorite_bp
from web.routes.watchlist_routes import watchlist_bp
from web.file_watcher import setup_file_watcher

app = Flask(__name__, 
    template_folder=str(Path(__file__).parent / 'templates'),
    static_folder=str(Path(__file__).parent / 'templates/dist/static')
)
CORS(app)  # 启用 CORS

# 注册蓝图
app.register_blueprint(udf_bp, url_prefix='/api/udf')
app.register_blueprint(chart_bp)
app.register_blueprint(favorite_bp)
app.register_blueprint(watchlist_bp)

TRADINGVIEW_BASE = 'https://trading-terminal.tradingview-widget.com'

def proxy_tradingview_file(path: str, base_dir: str) -> Response:
    """统一处理TradingView文件的代理和保存"""
    root_dir = Path(__file__).parent

    target_url = f'{TRADINGVIEW_BASE}/{base_dir}/{path}'
    local_file = root_dir / 'templates' / 'static' / base_dir / path
    local_file.parent.mkdir(parents=True, exist_ok=True)
    
    if not local_file.exists():
        with requests.get(target_url, stream=True) as resp:
            with open(local_file, 'wb') as f:
                for chunk in resp.iter_content(1024):
                    f.write(chunk)

    
    return send_from_directory(str(root_dir / 'templates' / 'static'), f'{base_dir}/{path}')

# TradingView代理
@app.route('/static/charting_library/<path:path>')
def proxy_charting_library(path):
    return proxy_tradingview_file(path, 'charting_library')

# TradingView datafeeds代理
@app.route('/static/datafeeds/<path:path>')
def proxy_datafeeds(path):
    return proxy_tradingview_file(path, 'datafeeds')

# 处理构建后的静态资源
@app.route('/dist/static/<path:path>')
def serve_dist_static(path):
    return send_from_directory('templates/dist/static', path)

# 基础图表路由
@app.route('/')
def index():
    return render_template('dist/index.html',)

@app.route('/chart/<symbol>')
def chart(symbol):
    return render_template('chart.html', symbol=symbol)


if __name__ == '__main__':
    # Setup file watcher for templates directory
    templates_dir = str(Path(__file__).parent / 'templates')
    observer = setup_file_watcher(app, templates_dir)
    
    try:
        app.run(
            host='0.0.0.0',
            port=5001,
            debug=True
        )
    finally:
        observer.stop()
        observer.join()